package com.wteam.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.wteam.PoJo.DO.*;
import com.wteam.PoJo.DTO.OrderDetailDTO;
import com.wteam.PoJo.DTO.OrderFormDTO;
import com.wteam.PoJo.DTO.orderpageDTO;
import com.wteam.PoJo.VO.orderDetialVO;
import com.wteam.PoJo.VO.orderGoodsVO;
import com.wteam.framework.common.exception.ServiceException;
import com.wteam.mapper.OrderDetailMapper;
import com.wteam.mapper.OrderMapper;
import com.wteam.Service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wteam.until.Result;
import com.wteam.until.UserContext;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表（现货） 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-07-16
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveoreder(OrderFormDTO orderFormDTO) {
        Long createorder = createorder(orderFormDTO);
        Long userid = UserContext.getUser();
        //删除购物车
        Db.lambdaUpdate(Cart.class)
                .eq(Cart::getUserId, userid)
                .eq(Cart::getChoose, true)
                .remove();
        return createorder;
    }

    @Override
    public Long oreder(OrderFormDTO orderFormDTO) {
        return createorder(orderFormDTO);
    }

    @Override
    public Result orderbystatus(orderpageDTO orderpage) {
//用户id
        Long userId = UserContext.getUser();
        Page<Order> page1 = orderpage.toMpPage();
        //查订单
        Page<Order> page = lambdaQuery().eq(Order::getUserId, userId)
                .eq(orderpage.getStatus() != 7, Order::getStatus, orderpage.getStatus())
                .page(page1);
        //订单列表
        List<Order> orders = page.getRecords();
        List<orderDetialVO> orderDetialVOS=new ArrayList<>(orders.size());
        for (Order order : orders) {
            orderDetialVO orderDetialVO=new orderDetialVO();
            orderDetialVO.setOrderid(order.getId());
            orderDetialVO.setStatus(order.getStatus());
            orderDetialVO.setAmount(order.getAmount());
            orderDetialVO.setPostage(order.getPostage());
            orderDetialVO.setActualPrice(order.getActualPrice());

            ///订单详情
            List<OrderDetail> orderDetailList = Db.lambdaQuery(OrderDetail.class)
                    .eq(OrderDetail::getOrderId, order.getId())
                    .list();
            //商品id
            List<Long> goodsid = orderDetailList.stream()
                    .map(OrderDetail::getGoodsId)
                    .collect(Collectors.toList());
            Map<Long, Integer> collect = orderDetailList.stream().collect(Collectors.toMap(OrderDetail::getGoodsId, OrderDetail::getNum));
            //查商品
            List<Goods> list = Db.lambdaQuery(Goods.class).in(Goods::getId, goodsid).list();
            List<orderGoodsVO>orderGoodsVOList=new ArrayList<>(list.size());

            for (Goods goods : list) {
                orderGoodsVO orderGoodsVO=new orderGoodsVO();
                BeanUtil.copyProperties(goods,orderGoodsVO);
                orderGoodsVO.setGoodsId(goods.getId());
                orderGoodsVO.setNum(collect.get(goods.getId()));
                orderGoodsVOList.add(orderGoodsVO);
            }
            orderDetialVO.setOrderGoodsVOS(orderGoodsVOList);
            orderDetialVOS.add(orderDetialVO);
        }

        return Result.success(orderDetialVOS);
    }

    @Override
    public Result buyorder(Long orderid) {
        lambdaUpdate().eq(Order::getId,orderid).set(Order::getStatus,2);
        return Result.success("支付成功");
    }

    public Long createorder(OrderFormDTO orderFormDTO) {
        //1.生成成订单表
        Order order = new Order();
        //1.1用户id
        Long userid = UserContext.getUser();
        //1.2算总价
        List<OrderDetailDTO> goodDetails = orderFormDTO.getDetails();
        //获取购买商品id和数量
        Map<Long, Integer> collect = goodDetails.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        //获取的
        Set<Long> goodsIds = collect.keySet();

        //根据商品id查商品详情
        List<Goods> list = Db.lambdaQuery(Goods.class)
                .in(Goods::getId, goodsIds)
                .list();
        //原价格
        BigDecimal totall = BigDecimal.valueOf(0);
        //2.1创建订单详情表
        List<OrderDetail> list1 = new ArrayList<>(list.size());

        for (Goods goods : list) {

            BigDecimal bigDecimal = BigDecimal.valueOf(collect.get(goods.getId()));
            totall = totall.add(goods.getPrice().multiply(bigDecimal));
            //2.2加订单详情表
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setGoodsId(goods.getId());
            orderDetail.setPrice(goods.getPrice());
            orderDetail.setNum(collect.get(goods.getId()));

            list1.add(orderDetail);
        }
        //查优惠卷
        BigDecimal subtract = totall;
        if (orderFormDTO.getVoucherId() != null) {
            Voucher voucher = Db.lambdaQuery(Voucher.class)
                    .eq(Voucher::getId, orderFormDTO.getVoucherId())
                    .one();
            //优惠后的价格
            subtract = totall.subtract(voucher.getDeno());
            //删用户拥有的优惠卷
            VoucherUser one = Db.lambdaQuery(VoucherUser.class)
                    .eq(VoucherUser::getVoucherId, orderFormDTO.getVoucherId())
                    .one();
            //判断优惠卷是不是大于1
            if (one.getNum() < 1) {
                throw new ServiceException("没有优惠卷");
            }

            Db.lambdaUpdate(VoucherUser.class)
                    .eq(VoucherUser::getVoucherId, orderFormDTO.getVoucherId())
                    .set(VoucherUser::getNum, one.getNum() - 1).update();

            order.setVoucherId(orderFormDTO.getVoucherId());
        }
        order.setUserId(userid);
        order.setStatus(1);
        order.setAmount(totall);
        order.setActualPrice(subtract);
        order.setPostage(orderFormDTO.getPostage());
        order.setAddressId(orderFormDTO.getAddressId());

        save(order);


        for (OrderDetail goods : list1) {
            //2.3 加订单id
            goods.setOrderId(order.getId());
            orderDetailMapper.insert(goods);
        }
        return order.getId();
    }
}


